package com.briup.impl.server;

import com.briup.entity.Environment;
import com.briup.impl.util.ConnectionUtil;
import com.briup.inter.server.DBStore;
import org.apache.log4j.Logger;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.*;
import java.util.stream.Collectors;


public class DBStoreImpl implements DBStore {
     Logger log = Logger.getLogger(DBStoreImpl.class);
    @Override
    public void saveDB(Collection<Environment> list) throws Exception {
        int count = 0;
        long start = System.currentTimeMillis();
        Connection conn = null;
        PreparedStatement ps = null;
        // 入库
        try {
            conn = ConnectionUtil.getConnection();
            conn.setAutoCommit(false); // 手动提交
            // 将大集合拆成小集合
            Map<Integer, List<Environment>> map = list.stream()
                    .collect(Collectors.groupingBy(
                            e -> e.getGather_date().toLocalDateTime().getDayOfMonth()
                    ));
            for (Map.Entry<Integer, List<Environment>> entry : map.entrySet()) { // map中是单表入库的代码
                Integer day = entry.getKey();
                List<Environment> smallList = entry.getValue();
                // env_detail_  变量 1
                String sql = "insert into table_"+day+"" +
                        "(name, src_id, des_id, dev_id, sersorAddress, count, cmd, data, status, gather_date) " +
                        "values(?,?,?,?,?,?,?,?,?,?)";
                // 预处理sql
                ps = conn.prepareStatement(sql);
                for (Environment e : smallList) {
                    ps.setString(1, e.getName());
                    ps.setString(2, e.getSrcId());
                    ps.setString(3, e.getDesId());
                    ps.setString(4, e.getDevId());
                    ps.setString(5, e.getSersorAddress());
                    ps.setInt(6, e.getCount());
                    ps.setString(7, e.getCmd());
                    ps.setFloat(8, e.getData());
                    ps.setInt(9, e.getStatus());
                    ps.setTimestamp(10,e.getGather_date());
                    ps.addBatch();
                    count++;
                    if(count % 200 == 0){ // 每200 持久化一次
                        ps.executeBatch();
                        conn.commit();
                    }
                }

                ps.executeBatch();
                conn.commit();
            }


        } catch (SQLException e) {
            try {
                conn.rollback();
            } catch (SQLException ex) {}
            e.printStackTrace();
        } finally {
            ConnectionUtil.close(conn,ps);
        }
        long end = System.currentTimeMillis();
        log.debug("入库成功 时间为" + (end-start) + "毫秒");
    }
}
